package com.stone.framework.auth.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.stone.framework.auth.service.LoginService;
import com.stone.framework.core.context.UserContext;
import com.stone.framework.message.ReqMessage;
import com.stone.framework.message.ResMessage;
import com.stone.framework.message.auth.LoginReqBody;
import com.stone.framework.message.auth.LoginResBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "登录")
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "登录", httpMethod = "POST")
    @PostMapping("/login")
    public ResMessage<LoginResBody> login(@Valid @RequestBody ReqMessage<LoginReqBody> reqMessage) {
        String jwtToken = loginService.login(reqMessage.getBody());
        return ResMessage.success(new LoginResBody(jwtToken));
    }

    @ApiOperation(value = "登出", httpMethod = "POST")
    @PostMapping("/logout")
    public ResMessage<Void> logout(@Valid @RequestBody ReqMessage<Void> reqMessage) {
        return ResMessage.success();
    }

    @ApiOperation(value = "获取验证码", httpMethod = "POST")
    @PostMapping("/getCaptcha")
    public ResMessage<String> getCaptcha(@Valid @RequestBody ReqMessage<String> reqMessage) {
        String imgBase64 = loginService.buildCaptcha(reqMessage.getBody());
        return ResMessage.success(imgBase64);
    }

    /**
     * TODO 功能待完善
     * 
     * @return
     */
    @ApiOperation(value = "刷新token", httpMethod = "POST")
    @PostMapping("refreshToken")
    public ResMessage<String> refreshToken() {
        String token = loginService.getToken(UserContext.getDefaultUsername(), UserContext.getTerminal());
        return ResMessage.success(token);
    }

}
